<!DOCTYPE html>
<html>

<head>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
    }

    th,
    td {
      border: 1px solid black;
      padding: 8px;
      text-align: left;
    }
  </style>
</head>

<body>

  <table>
    <tr>
      <th>姓名</th>
      <th>年龄</th>
      <th>职业</th>
    </tr>
    <tr>
      <td>张三</td>
      <td>25</td>
      <td>工程师</td>
    </tr>
    <tr>
      <td>李四</td>
      <td>30</td>
      <td>设计师</td>
    </tr>
  </table>

  <button onclick="exportToExcel()">导出到Excel</button>

  <script>
    function exportToExcel() {
      const table = document.querySelector("table");
      const rows = table.querySelectorAll("tr");

      let csvContent = "data:text/csv;charset=utf-8,";

      rows.forEach((row) => {
        const rowData = [];
        const columns = row.querySelectorAll("th, td");

        columns.forEach((column) => {
          rowData.push(column.innerText);
        });

        csvContent += rowData.join(",") + "\n";
      });

      const encodedUri = encodeURI(csvContent);
      const link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", "table_data.csv");
      document.body.appendChild(link);
      link.click();
    }
  </script>

</body>

</html>